<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>1.forEach重写</title>
</head>
<body>
  <script>
    // 原生forEach
    var arr = [1,2,3]
    var obj = {}

    // arr.forEach(function(item, i, arr) {
    //   console.log(item, i, arr, this);
    // }, obj)

    // 重写forEach
    Array.prototype.myforEach = function(fn) {
      // 1.拿到arr
      var arr = this
      // 确定this指向
      var context = arguments[1] || window

      if (typeof fn === 'function') {
        for (let i = 0;i<arr.length;i++) {
          fn.apply(context, [arr[i], i, arr])
        }
      } else {
        throw new Error("参数必须是function")
      }
    }

    arr.myforEach(function(item, i, arr) {
      console.log(item, i, arr, this);
      
    }, obj)








  </script>
  
</body>
</html>